package top.yesjava.webfinal.dao;

import top.yesjava.webfinal.common.utils.MyDbUtil;
import top.yesjava.webfinal.common.utils.PageInfo;
import top.yesjava.webfinal.entity.Student;

import java.sql.Connection;
import java.util.List;

public class StudentDao {
    public Student selectStudentById(Integer id) {
        String sql = " SELECT id, name, stuNo, sex, reg_time 'regTime' FROM student where id = ? ";
        List<Student> students = MyDbUtil.executeQuery(Student.class, sql,id);
        return students.size()>0?students.get(0):null;
    }

    public List<Student> selectAllStudents() {
        String sql = " SELECT id, name, stuNo, sex, reg_time 'regTime' FROM student ";
        List<Student> students = MyDbUtil.executeQuery(Student.class, sql);
        return students;
    }


    public PageInfo<Student> selectStudentsByPage(int pageNo, int pageSize) {
//        小问题，演示项目是发现不了。用两个新 连接去查询两个sql语句
        Connection connection = MyDbUtil.getConnection();
        String sqlCount = " SELECT count(*)  FROM student ";//仅仅是查询一个数值
        String sql = " SELECT id, name, stuNo, sex, reg_time 'regTime' FROM student limit ?,? ";
        List<Student> studentList = MyDbUtil.executeQuery(connection,Student.class, sql, (pageNo - 1) * pageSize, pageSize);
        long count = (Long) MyDbUtil.executeQueryOneValue(connection,sqlCount);
        PageInfo<Student> pageInfo = new PageInfo<>(pageNo, pageSize, (int)count, studentList);
        MyDbUtil.closeConnection();
        return pageInfo;
    }

//    可变长度参数，数组的进化
    public void delStudents(Integer... id){
        String sql = " DELETE from student where id  in (    " ;
        if(id!=null && id.length>0){
            for (int i = 0; i < id.length; i++) {
                sql = sql +"? ,";
            }
        }
        if(sql.endsWith(",")){
            sql = sql.substring(0,sql.lastIndexOf(","));
        }
        sql = sql +   ") ";
        MyDbUtil.executeUpdate(sql,id);
        System.out.println(sql);
    }

}
/*
页码：pageNO  1
页条数量：pageSize  5
总数： count
页数 :   (count/pageSize) + (count%pageSize==0) ? 0 : 1
展示数据： List
写一个分页器 封装以上的信息
-------------------

select count(*) ..                      count
select ..... limit (pageNO-1) * pageSize, pageSize  -- > list

 */
